import logging
import os
import time
from pathlib import Path
from time import sleep

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

from extract_file import extract_and_copy, setup_logging
from tool import get_filname, is_sn_valid

# 配置信息
LOGIN_URL = "https://iot-admin.zuoyebang.cc/iot-admin-server/index"
DEVICE_ID = "你的设备唯一ID"  # 替换为实际设备ID
USERNAME = "xx"  # 替换为实际用户名
PASSWORD = "xx"  # 替换为实际密码
DOWNLOAD_WAIT_TIME = 120  # 等待下载的时间(秒)
PHONE = "xx"   # 替换为通知手机号
chromedriver_path = r"D:\实习生工作\chromedriver-win32\chromedriver.exe"  # 替换为你实际的 chromedriver 路径

def init_browser():
    """
    初始化并配置浏览器

    Returns:
        webdriver.Chrome: 配置好的浏览器实例
    """
    # 配置Chrome选项
    chrome_options = webdriver.ChromeOptions()
    # 设置下载路径（可选）
    prefs = {
        "download.default_directory": r"D:\实习生工作",  # 替换为你想要的下载路径
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.enabled": True,
    }
    chrome_options.add_experimental_option("prefs", prefs)
    chrome_options.add_experimental_option("detach", True)
    # chrome_options.add_argument('--headless')

    # 初始化浏览器
    driver = webdriver.Chrome(service=Service(chromedriver_path), options=chrome_options)

    driver.maximize_window()
    return driver


def login(driver: webdriver.Chrome, username: str, password: str) -> None:
    """
    登录网站

    Args:
        driver: 浏览器实例
        username: 登录用户名
        password: 登录密码
    """
    driver.get(LOGIN_URL)
    try:
        # 等待页面加载
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "el-input__inner"))
        )

        # 输入用户名和密码
        driver.find_element(By.XPATH, "//input[@placeholder='请输入邮箱前缀']").send_keys(username)
        driver.find_element(By.XPATH, "//input[@placeholder='请输入密码']").send_keys(password)

        # 点击登录按钮（根据实际页面调整选择器）
        login_button = driver.find_element(By.CSS_SELECTOR, "button[type='button']")
        login_button.click()
        sleep(1)
    except Exception as e:
        print(f"登录失败: {str(e)}")


def download_logs(driver: webdriver.Chrome) -> tuple[str, str]:
    """
    下载设备日志文件

    Args:
        driver: 浏览器实例

    Returns:
        tuple: 包含设备ID和下载的文件名
    """
    # 发送日志上传通知
    driver.get("https://iot-admin.zuoyebang.cc/iot-admin-server/system/errorlog/table")
    # 第一个输入框
    first_sn_input = driver.find_element(By.XPATH, '//*[@id="form-key-get"]/div/div/div/div[1]/input')
    # 第二个输入框
    second_sn_input = driver.find_element(By.XPATH, '//*[@id="form-search"]/div/ul/li[1]/input')

    driver.find_element(By.XPATH, '//*[@id="form-key-get"]/div/div/div/div[3]/input').send_keys(PHONE)

    device_id = ""
    while True:
        device_id = input("请输入id号: ")
        if device_id.lower() == 'y':
            print("程序已终止。")
            driver.quit()
            return
        if not is_sn_valid(device_id):
            print(f"{device_id} 不符合要求，请重新输入SN号")
            continue
        break
    first_sn_input.send_keys(device_id)

    message = "设备不在线"
    click_count = 1
    while True:
        # 发送日志上传通知
        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH, '/html/body/div[2]/div/button')
            )
        ).click()
        # 处理通知提示框
        message = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, f'//*[@id="layui-layer{click_count}"]/div[2]'))
        ).text
        print(message)
        # 确认消息
        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, f'//*[@id="layui-layer{click_count}"]/div[3]/a'))
        ).click()
        click_count += 1
        if "设备不在线" in message:
            user_input = input("设备不在线，请确认设备在线后输入任意字符继续（q退出,enter继续）: ")
            if user_input.strip().lower() == 'q':
                print("用户选择退出程序。")
                driver.quit()
                exit(0)
        else:
            break
    second_sn_input.send_keys(device_id)

    # 点击搜索按钮
    WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable(
            (By.XPATH, '//*[@id="form-search"]/div/ul/li[2]/a[1]'))
    ).click()

    # 下载文件
    try:
        download_links = WebDriverWait(driver, 10).until(
            EC.presence_of_all_elements_located((By.XPATH, '//*[@id="bootstrap-table"]/tbody/tr/td[6]/a'))
        )
        index = len(download_links) // 2
        download_link = download_links[index]
        download_link.click()
        filename = get_filname(download_link.get_attribute("href"))
        print(filename)
        return device_id, filename
    except Exception as e:
        logging.error(f" 下载文件时出错: {str(e)}")
        return None, None


def extract_triger(device_id: str, filename: str,baseDir: Path = Path.cwd()) -> bool:
    """
    触发日志文件的解压和复制

    Args:
        device_id: 设备ID
        filename: 下载的日志文件名
        baseDir: 设置工作目录，默认为当前目录

    Returns:
        bool: 操作是否成功
    """
    while filename not in os.listdir(baseDir):
        sleep(1)
    zip_file_path = baseDir / filename
    output_dir = baseDir / device_id

    return extract_and_copy(zip_file_path, baseDir, output_dir)


def main() -> None:
    """
    主函数，协调整个日志下载和处理流程
    """
    try:
        setup_logging()
        # 初始化浏览器
        driver = init_browser()

        # 登录网站
        login(driver, USERNAME, PASSWORD)

        count = 0
        while True:
            # 下载日志
            device_id, filename = download_logs(driver)
            if device_id is None or filename is None:
                continue
            # 日志筛选
            if extract_triger(device_id, filename, Path("D:/实习生工作")):
                count += 1
                msg = f"第{count}台设备日志收集成功，SN: {device_id}"
                logging.info(msg)
                print(msg)
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        # 关闭浏览器
        driver.quit()
        pass


if __name__ == "__main__":
    main()